#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from threading import Thread

__author__ = 'teffy'

'''
@filename email
@@created on 2018-01-14
@poject:python_flask_demo
@auther:teffy
'''

from flask import current_app, render_template
from flask_mail import Message

from . import mail


def send_mail(to, subject, template, **kwargs):
    app = current_app._get_current_object()
    sender = app.config['MAIL_USERNAME']
    subject = app.config['FLASK_MAIL_SUBJECT_PREFIX'] + subject
    msg = Message(subject=subject,
                  sender=sender,
                  recipients=[to])
    msg.body = render_template(template + '.txt', **kwargs)
    msg.html = render_template(template + '.html', **kwargs)
    thr = Thread(target=send_async_email, args=[app, msg])
    thr.start()
    return thr


def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)
    print('Email has been sent!')
